package com.xy.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * 当前过滤器是用于检测请求的发送时间和服务器收到的时间的差是否超过了阈值
 * @Author: xiaoyang
 * @Date: 2022/11/20/19:21
 * @Description:
 */
@Component
public class TimeStampFilter extends ZuulFilter {

    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+50;
    }

    @Override
    public boolean shouldFilter() {

        //如果前面的过滤器拦截了  这个过滤器是否执行取决于前面的过滤器是否成功
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean zuulResponse = currentContext.sendZuulResponse();
        return zuulResponse;
    }

    @Override
    public Object run() throws ZuulException {


        // TODO: 2022/11/20
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String timestamp = request.getParameter("timestamp");//我们需要yyyy-MM-dd HH:mm:ss
        try {
            Date date = simpleDateFormat.parse(timestamp);
            long time = date.getTime();//获取到毫秒值
            long currenTime = System.currentTimeMillis();//当前系统毫秒值

            if (currenTime - time > 60000) {

                currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
                currentContext.setSendZuulResponse(false);
                currentContext.setResponseBody("时间超过阈值");
            }
 

        } catch (ParseException e) {
            e.printStackTrace();
//            currentContext.addZuulRequestHeader("content-Type","text/html;charset=utf-8");
            currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            currentContext.setResponseBody("时间超过阈值");
        }



        return null;
    }
}
